/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.mapdemo;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.reflect.TypeToken;
import com.gy.paidao.BaseActivity;
import com.gy.paidao.MyApplication;
import com.gy.paidao.bean.BaseBean;
import com.gy.paidao.main.BabbleDetailActivity;
import com.gy.paidao.main.bean.ActivityBean;
import com.gy.paidao.main.view.MapDetailMarker;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.GoogleLocationUtil;
import com.gy.paidao.util.IMFileModel;
import com.gy.paidao.util.IMUploadSuccessListener;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.MarkerBitmapUpdataManager;
import com.gy.paidao.util.SPHelper;
import com.gy.paidao.util.Urls;
import com.gy.paidao.util.ViewToBitmaputil;
import com.jky.struct2.http.core.AjaxParams;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


public class BasicMapDemoActivity extends BaseActivity implements
        OnMapReadyCallback,GoogleMap.OnCameraChangeListener ,GoogleMap.OnMarkerClickListener{


    private List<ActivityBean> datas, requestList;
    private String userLoginID;
    private GoogleMap map;
    private View markderView;
    private ImageView imgLoc;
    private boolean isShow =false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.basic_demo);

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        setViews();
        dorequestActivity();
        openGPSSettings();
    }

    @Override
    protected void initVariable() {
        userLoginID = SPHelper.getInstance(this).getStringData("userLoginID", null);
        datas = new ArrayList<ActivityBean>();
        requestList = new ArrayList<ActivityBean>();
    }

    @Override
    protected void setTitleViews() {

    }

    @Override
    protected void setViews() {
        imgLoc = (ImageView) findViewById(R.id.map_img_loc);
        imgLoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showToast("正在定位，请稍后...");
                GoogleLocationUtil.getInstance(getApplicationContext()).addLocationListener(new GoogleLocationUtil.OnLocationListener() {
                    @Override
                    public void onAmapLocationListener(Location aMapLocation) {
                        LogUtil.e("地图定位成功-----");
                        MyApplication.CURRENT_X = aMapLocation.getLongitude() + "";
                        MyApplication.CURRENT_Y = aMapLocation.getLatitude() + "";
                        LatLng sydney = new LatLng(Double.valueOf(MyApplication.CURRENT_Y),
                                Double.valueOf(MyApplication.CURRENT_X));
                        map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 15));
                        dorequestActivity();
                    }

                    @Override
                    public void onAmapLocationFail() {

                    }
                });
            }
        });
    }


    @Override
    public void onMapReady(final GoogleMap map) {
        this.map = map;
        map.setOnCameraChangeListener(BasicMapDemoActivity.this);
        map.setOnMarkerClickListener(BasicMapDemoActivity.this);
        if(TextUtils.isEmpty(MyApplication.CURRENT_Y) || TextUtils.isEmpty(MyApplication.CURRENT_X)){
            LogUtil.e("地图开始定位-------");
            GoogleLocationUtil.getInstance(getApplicationContext()).addLocationListener(new GoogleLocationUtil.OnLocationListener() {
                @Override
                public void onAmapLocationListener(Location aMapLocation) {
                    LogUtil.e("地图定位成功-----");
                    MyApplication.CURRENT_X = aMapLocation.getLongitude() + "";
                    MyApplication.CURRENT_Y = aMapLocation.getLatitude() + "";
                    LatLng sydney = new LatLng(Double.valueOf(MyApplication.CURRENT_Y),
                            Double.valueOf(MyApplication.CURRENT_X));
                    map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 15));
//                    map.addMarker(new MarkerOptions().position(sydney).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
                }

                @Override
                public void onAmapLocationFail() {

                }
            });
        } else {
            LatLng sydney = new LatLng(Double.valueOf(MyApplication.CURRENT_Y),
                    Double.valueOf(MyApplication.CURRENT_X));
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 15));
//            map.addMarker(new MarkerOptions().position(sydney).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
            map.setOnCameraChangeListener(this);
            map.setOnMarkerClickListener(this);
        }

    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    private void openGPSSettings() {
        LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            return;
        } else {
            Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
            startActivityForResult(intent, 0); //此为设置完成后返回到获取界面
        }
    }

    /**
     * 请求列表
     */
    private void dorequestActivity() {
        showLoading();
        params = new AjaxParams();
        params.put("latitude", MyApplication.CURRENT_Y+"");
        params.put("longitude",MyApplication.CURRENT_X+"");
//        params.put("latitude", "39.963053");
//        params.put("longitude", "116.477316");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.get(Urls.url_map_list, params, callBack, 0);
    }

    @Override
    protected void handlerBean(int requestCode, BaseBean baseBean) {
        super.handlerBean(requestCode, baseBean);
        if (baseBean.success) {
            String data = String.valueOf(baseBean.data);
            switch (requestCode) {
                case 0://请求列表
                    if (!TextUtils.isEmpty(data)) {
                        if (!TextUtils.isEmpty(data) && !"[]".equals(data)) {
                            Type type = new TypeToken<List<ActivityBean>>() {
                            }.getType();
                            requestList = gson.fromJson(data, type);

                            for (ActivityBean bean : requestList) {
                                bean.setX(bean.longitude + "");
                                bean.setY(bean.latitude + "");
                            }
                            addMarker();
                            for (int i = 0; i < requestList.size(); i++) {
                                final int finalI = i;
                                if ("image".equals(requestList.get(i).mediaType)) {
                                        IMFileModel.getInstance(BasicMapDemoActivity.this).downFile(requestList.get(i).mediaPaths, new IMUploadSuccessListener() {
                                            @Override
                                            public void messageUploadFileSuccess(String url) {
                                                LogUtil.e("加载成功------" + finalI+"  "+url);
                                                requestList.get(finalI).localPath = url;
                                                isShow = true;
                                                handler.sendEmptyMessage(0);
                                            }

                                            @Override
                                            public void messageUploadFail(String path) {
                                                LogUtil.e("加载失败-----");
                                                requestList.get(finalI).localPath = "";
//                                                if (finalI == requestList.size() - 1) {
//                                                    addMarker();
//                                                }
                                                isShow = true;
                                                handler.sendEmptyMessage(0);
                                            }
                                        }, "png", requestList.get(i).id + "");
                                } else if ("video".equals(requestList.get(i).mediaType)) {
                                        IMFileModel.getInstance(BasicMapDemoActivity.this).downFile(requestList.get(i).thumbnailUrl, new IMUploadSuccessListener() {
                                            @Override
                                            public void messageUploadFileSuccess(String url) {
                                                LogUtil.e("加载成功------" + finalI+"  "+url);
                                                requestList.get(finalI).localPath = url;
                                                isShow = true;
                                                handler.sendEmptyMessage(0);
                                            }

                                            @Override
                                            public void messageUploadFail(String path) {
                                                LogUtil.e("加载失败-----");
                                                requestList.get(finalI).localPath = "";
//                                                if (finalI == requestList.size() - 1) {
//                                                    addMarker();
//                                                }
                                                isShow = true;
                                                handler.sendEmptyMessage(0);
                                            }
                                        }, "png", requestList.get(i).id + "");
                                }
                            }
                        }
                    }
                    break;
            }
        } else {
            if (!TextUtils.isEmpty(baseBean.errMsg)) {
                showToast(baseBean.errMsg);
            }
        }
    }

    MarkerBitmapUpdataManager.MarkerBitmapUpdataListener markerBitmapUpdataListener = new MarkerBitmapUpdataManager.MarkerBitmapUpdataListener() {
        @Override
        public void markerUpdate(int id) {
            if (requestList.size() > 0) {
                ActivityBean bean = requestList.get(requestList.size() - 1);
                if (bean.id == id) {
                    addMarker();
                }
            }
        }
    };


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(isShow){
                isShow = false;
            } else {
                return;
            }
            int i = 0;
            for (ActivityBean bean : requestList) {
                if (!TextUtils.isEmpty(bean.localPath)) {
                    i++;
                } else {
                    if ("image".equals(requestList.get(i).mediaType)) {
                        if(TextUtils.isEmpty(requestList.get(i).mediaPaths)){
                            i++;
                        }
                    } else {
                        if(TextUtils.isEmpty(requestList.get(i).thumbnailUrl)){
                            i++;
                        }
                    }
                }
            }

            if (i == requestList.size()) {
                addMarker();
            }
        }
    };

    private void addMarker(){
        map.clear();
        for (int i = 0; i < requestList.size(); i++) {
            addMarkerView(requestList.get(i),i);
        }
        LogUtil.e("finish=======");
    }

    private void addMarkerView(ActivityBean bean,int id){
        markderView = View.inflate(this,R.layout.view_marker,null);
        ImageView img = (ImageView) markderView.findViewById(R.id.view_marker_img);
        if(!TextUtils.isEmpty(bean.localPath)){
            if(!"error".equals(bean.localPath)){
                Bitmap bitmaps = BitmapFactory.decodeFile(bean.localPath);
                img.setImageBitmap(bitmaps);
            }
        }
        LatLng sydney = new LatLng(Double.valueOf(bean.getY()),
                Double.valueOf(bean.getX()));
        map.addMarker(new MarkerOptions().position(sydney).title(id+"")
                .icon(BitmapDescriptorFactory.fromBitmap(ViewToBitmaputil.getViewBitmap(markderView,100,100))));
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        int loc = Integer.valueOf(marker.getTitle());
        Intent intent = new Intent(this, BabbleDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("activity", requestList.get(loc));
        intent.putExtras(bundle);
        startActivity(intent);
        AnimUtil.pushLeftInAndOut(this);
        return true;
    }
}
